import java.sql.*;
import java.util.Scanner;
import java.util.*;

public class Chat{

    private static  Scanner sc = new Scanner(System.in);
    private static ChatDB db = new ChatDB();
    private static TimerTask getMessages = new displayMessages();
    private static Timer timer = new Timer();
    private static String userName;
    public static void login()
    {
        //String user;
        System.out.print("Please enter login name: ");
        userName = sc.next();
        
        //return (user);
    }   
    
    public static void message(String user) throws Exception
    {
        //get message
        for(int x = 1; x <60;x++)
        {
           System.out.println("");
        }
        ResultSet rs = db.getMessage();
        
        while(rs.next())
        {
            System.out.println(rs.getString(2) + ": " + rs.getString(3));
        }        

        //send message
        System.out.print("Enter message:");
        db.sendMessage(userName,sc.nextLine());
    }


    public static void main (String args[]) throws Exception
    {   
       // String userName;
       // userName = login();
        login();
//        System.out.println(userName);

        timer.schedule(getMessages,50,2000);
       // while(true)
       // {        
           // message(userName);
        //}
    }
    public static class displayMessages extends TimerTask
    {
        public void run(){
           // System.out.println("GETTING MESSAGES");   
        try{
          //get message
          for(int x = 1; x <60;x++)
          {
             System.out.println("");
          }
          ResultSet rs = db.getMessage();
 
          while(rs.next())
          {
              System.out.println("\t" + rs.getString(2) + ":   " + rs.getString(3));
          }
 
          //send message
          System.out.print("\n\n\nEnter message:");
          if(sc.hasNext())
          {
              db.sendMessage(userName,sc.nextLine());
          }
          else{
            run();  
          }
         }
        catch(Exception e) {}

        }
    }
}
